import {
  BetaSchemaForm,
  ModalForm,
  ModalFormProps,
  ProFormInstance,
} from '@ant-design/pro-components';

import React, { forwardRef, ReactNode, useImperativeHandle, useRef, useState } from 'react';

export type SchemaFormModalProps = {
  modalProps?: Omit<ModalFormProps, 'onFinish'>;
  fields: FieldProps[];
  children?: React.ReactNode;
  append?: React.ReactNode;
  onFinish?: (record: Record<string, any>, params?: Record<string, any>) => Promise<boolean> | void;
};

export interface SchemaFormModalRef {
  show: (
    originalData: Record<string, any>,
    params?: Record<string, any>,
    // 在参数中处理表单提交 仅在props.onFinish为空时有效
    onFinish?: (record: Record<string, any>, params?: Record<string, any>) => Promise<boolean>,
  ) => void;
  setFieldValue: (name: any, value: any) => void;
  dismiss: () => void;
}

// 表单modal
const SchemaFormModal = (
  props: SchemaFormModalProps,
  ref: React.Ref<SchemaFormModalRef>,
): JSX.Element => {
  const tempRef = useRef<ProFormInstance | undefined>(null);
  const [isShow, setIsShow] = useState(false);
  const [extraParams, setExtraParams] = useState<Record<string, any>>();
  const modalFormRef = props.modalProps?.formRef || tempRef;
  // 此state存放一个函数, 由于setState的值为一个函数时react会自动调用函数来获取结果,所以使用setState储存一个函数时应该写成setState(()=> funcation)
  const [finish, setFinish] = useState<any>();

  useImperativeHandle(
    ref,
    () => ({
      /**
       * 展示变更弹窗
       * @param originalData 初始化数据
       */
      show: (
        initData: Record<string, any>,
        params?: Record<string, any>,
        onFinish?: (record: Record<string, any>, params?: Record<string, any>) => Promise<boolean>,
      ) => {
        console.log('show', initData, params);
        setExtraParams(params);
        modalFormRef?.current?.resetFields();
        modalFormRef?.current?.setFieldsValue(initData);
        setIsShow(true);
        setFinish(() => onFinish);
      },
      setFieldValue: (name: any, value: any) => {
        modalFormRef.current?.setFieldValue(name, value);
      },
      dismiss: () => {
        setIsShow(false);
      },
    }),
    [modalFormRef],
  );

  const onPressFinish = async (res: any) => {
    if (props.onFinish) {
      const result = props.onFinish(res, extraParams);
      if (!result) {
        return true;
      }
      return await result;
    }
    if (finish) {
      return await finish(res, extraParams);
    }
    return true;
  };

  return (
    <ModalForm
      width="520px"
      formRef={modalFormRef}
      open={isShow}
      style={{ maxHeight: '70vh', overflowY: 'scroll', padding: '20px' }}
      onOpenChange={(open: boolean) => {
        setIsShow(open);
      }}
      modalProps={{ forceRender: true }}
      onFinish={onPressFinish}
      grid
      {...props.modalProps}
    >
      {props.children as ReactNode}
      <BetaSchemaForm columns={props.fields as any} type="change" layoutType="Embed" />
      {props.append as ReactNode}
    </ModalForm>
  );
};

export default forwardRef(SchemaFormModal);
